var express = require('express');
var router = express.Router();
const os = require('os');
var moment = require('moment');
let { FormatData, isArrayEmpty, urlf2z, urlf2zList } = require('../util.js');
let {
  //管理员 
  isAdminLogin, getAdminCount, GetAdminList, GetAdminById, UpdateAdminById, addAdmin, DeleteAdminById,
  //轮播图
  getSwiperList, uploadSwiperImg, updataSwiperImg, deleteSwiperById, updataSwiperWz, getSwiperIdByIndex,
  //用户
  getUserCount, getUserList, GetUsersById, DeleteUserById,
  addRticlea, getRticleaById, deleteRticleaById, updataRticlea, getRticleaList, getRticleatCount,
  //敏感词
  getSensitiveAll, addSensitive, delSensitive,
  getInfoCount, getInfoList, getInfoById, deleteinfoById,
  getUserListWord
} = require('../mysql/index');
let upload = require('../util/multer/index')

router.post('/isAdminLogin', async (req, res, next) => {
  let { username, password, code } = req.body;
  try {
    const sessionCaptcha = req.session.captcha.toLowerCase();
    code = String(code).toLowerCase()
    if (sessionCaptcha != code) {
      return res.json({
        flog: 0,
        data: '验证码不正确'
      });
    }
  } catch (error) {
    return res.json({
      flog: 0,
      data: '验证码不正确'
    });
  }
  let data = await isAdminLogin({
    username,
    password
  });
  if (isArrayEmpty(data)) {
    jsonData = {
      code: 0,
      data: "账号或者密码错误"
    }
  } else {
    jsonData = {
      code: 1,
      data: {
        "access_token": username,
        "name": username,
        "userId": data[0].id
      }
    }
    req.session.AdminInfo = {
      username: username,
      userId: data[0].id,
      url: data[0].url
    }
  }
  return res.json(jsonData)
});

router.get('/adminInfo', async (req, res, next) => {
  if (!req.session.AdminInfo) {
    return res.json({
      code: 500,
      msg: "未登录"
    })
  }
  res.json(
    {
      "code": 200,
      "user": {
        "userId": req.session.AdminInfo.userId,
        "username": req.session.AdminInfo.username,
        "nickName": req.session.AdminInfo.username,
        "url": req.session.AdminInfo.url,
        "type": req.session.AdminInfo.type
      }
    }
  )
});

router.get('/getUserList', async (req, res, next) => {
  let { page, limit, userId, userName, userSex } = req.query;
  let count = await getUserCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getUserList(num, limit, {
    userId, userName, userSex
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetUsersById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetUsersById(id);
  res.json({
    code: 1,
    data
  })
})

router.get('/DeleteUserById', async (req, res, next) => {
  let id = req.query.userId;
  let data = await DeleteUserById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminPassById', async (req, res, next) => {
  let { oldPsw, newPsw } = req.body;
  let id = req.session.AdminInfo.userId;
  let username = req.session.AdminInfo.username;
  let admin = await isAdminLogin({
    username,
    password: oldPsw
  });
  if (admin.length) {
    await UpdateAdminById(id, {
      password: newPsw
    })
    return res.json({
      code: 200,
      msg: "修改密码成功"
    })
  } else {
    return res.json({
      code: 500,
      msg: "旧密码错误"
    })
  }
})

router.get('/GetAdminList', async (req, res, next) => {
  let { page, limit, id, name } = req.query;
  let count = await getAdminCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 1,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await GetAdminList(num, limit, {
    id, name
  });
  res.json({
    code: 0,
    data: data.data,
    count: data.count
  })
})

router.get('/GetAdminById', async (req, res, next) => {
  let id = req.query.editNo;
  let data = await GetAdminById(id);
  res.json({
    code: 1,
    data
  })
})

router.post('/UpdateAdminById', upload.single('url'), async (req, res, next) => {
  let { id, name, password, sex, url } = req.body;
  console.log(req.file)
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await UpdateAdminById(id, { name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.post('/DeleteAdminById', async (req, res, next) => {
  let { id } = req.body;
  await DeleteAdminById(id);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/addAdmin', upload.single('url'), async (req, res, next) => {
  let { name, password, sex, url } = req.body;
  url = req.file ? urlf2z(`${req.protocol}://${req.headers.host}/${req.file.path}`) : '';
  let data = await addAdmin({ name, password, sex, url });
  res.json({
    code: 1,
    data
  })
})

router.post('/uploadSwiperImg', upload.single('file'), async (req, res, next) => {
  let url = `${req.protocol}://${req.headers.host}/${req.file.path}`;
  url = urlf2z(url)
  let data;
  if (req.body.swiperId) {
    data = await updataSwiperImg(req.body.swiperId, {
      swiperurl: url
    })
  } else {
    data = await uploadSwiperImg({
      swiperurl: url
    })
    await updataSwiperImg(data.insertId, {
      swiperIndex: data.insertId
    })
  }
  res.json({
    code: 1,
    url: url,
    swiperId: data.insertId
  })
})

router.get('/getSwiperList', async (req, res, next) => {
  let data = await getSwiperList();
  res.json({
    code: 1,
    data
  })
})

router.post('/deleteSwiperById', async (req, res, next) => {
  let { swiperId } = req.body;
  await deleteSwiperById(swiperId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/updataSwiperWz', async (req, res, next) => {
  let { swiperId, toswiperId } = req.body
  let arr = []
  let swiperIndex = await getSwiperIdByIndex(swiperId)
  let toswiperIndex = await getSwiperIdByIndex(toswiperId)
  arr.push({
    swiperId: swiperId,
    swiperIndex: toswiperIndex
  }, {
    swiperId: toswiperId,
    swiperIndex: swiperIndex
  })
  await updataSwiperWz(arr)
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getRticleaList', async (req, res, next) => {
  let { page, limit, rticleaTitle } = req.query;
  var num = (page - 1) * limit;
  let data = await getRticleaList(num, limit, {
    rticleaTitle
  });
  res.json({
    code: 0,
    data: FormatData(data.data, {
      rticleaImgList: 'json',
      rticleaTime: 'date'
    }),
    count: data.count
  })
})

router.post('/addRticlea', upload.array('rticleaImg', 10), async (req, res, next) => {
  let countFile = req.files.length;
  let { rticleaTitle, rticleaTime, rticleaComm, adminId } = req.body;
  adminId = req.session.AdminInfo.userId
  if (countFile === 0) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  let rticleaImgList = urlf2zList(req);
  rticleaImgList = JSON.stringify(rticleaImgList);
  await addRticlea({
    rticleaTitle, rticleaTime, rticleaComm, adminId,
    rticleaImgList: rticleaImgList,
  })
  res.json({
    code: 1,
    data: "添加成功"
  })
})

router.get('/getRticleaById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await getRticleaById(editNo);
  res.json({
    code: 1,
    data: FormatData(data, {
      rticleaImgList: 'json',
      rticleaTime: 'date'
    })
  })
})

router.post('/deleteRticleaById', async (req, res, next) => {
  let { rticleaId } = req.body
  await deleteRticleaById(rticleaId)
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/getSensitiveAll', async (req, res, next) => {
  let data = await getSensitiveAll();
  res.json({
    code: 1,
    data
  })
})

router.post('/addSensitive', async (req, res, next) => {
  let { val } = req.body;
  let info = await addSensitive({
    sensitiveTag: val
  });
  if (!info.affectedRows) {
    return res.json({
      code: 0,
      data: "不能重复添加敏感词"
    })
  } else {
    res.json({
      code: 1,
      data: info
    })
  }
})

router.post('/delSensitive', async (req, res, next) => {
  let { sensitiveId } = req.body;
  await delSensitive(sensitiveId);
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.get('/getInfoList', async (req, res, next) => {
  let { page, limit, infoTitle } = req.query;
  let count = await getInfoCount();
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: []
    });
  }
  var num = (page - 1) * limit;
  let data = await getInfoList(num, limit, {
    infoTitle
  });
  res.json({
    code: 0,
    data: FormatData(data.data, {
      infoImgList: 'json',
      infoTime: 'date'
    }),
    count: data.count
  })
})

router.get('/getInfoById', async (req, res, next) => {
  let { editNo } = req.query;
  let data = await getInfoById(editNo);
  res.json({
    code: 1,
    data: FormatData(data, {
      infoImgList: 'json',
      infoTime: 'date'
    })
  })
})

router.post('/deleteinfoById', async (req, res, next) => {
  let { infoId } = req.body
  await deleteinfoById(infoId)
  res.json({
    code: 1,
    data: "删除成功"
  })
})

router.post('/updataRticlea', upload.array('rticleaImg', 10), async (req, res, next) => {
  let { rticleaTitle, rticleaTime, rticleaType, rticleaComm, rticleaImgList, rticleaId } = req.body;
  let rticleaImgListUpdate = urlf2zList(req);
  rticleaImgList = JSON.parse(rticleaImgList);
  rticleaImgList = rticleaImgList.concat(rticleaImgListUpdate);
  rticleaImgList = JSON.stringify(rticleaImgList);
  if (!rticleaImgList.length) {
    return res.json({
      code: 0,
      msg: "至少上传一张图片"
    })
  }
  await updataRticlea(rticleaId, {
    rticleaTitle, rticleaTime, rticleaType, rticleaComm, rticleaImgList
  })
  res.json({
    code: 1,
    data: "修改成功"
  })
})

router.get('/getIndexCount', async (req, res, next) => {
  let adminNum = await getAdminCount();
  let infoNum = await getInfoCount();
  let rticleatNum = await getRticleatCount();
  let userNum = await getUserCount();
  res.json({
    code: 1,
    adminNum, infoNum, rticleatNum, userNum
  })
})

router.get('/getuserNumTable', async (req, res, next) => {
  let DayList = [];
  for (var i = 1; i <= 7; i++) {
    DayList.push(moment().isoWeekday(i))
  }
  let { count, data } = await getUserListWord();
  let userNum = []
  DayList.forEach(dayItem => {
    let sunNum = 0;
    data.forEach(item => {
      if (dayItem.isSame(item.userTime, 'day')) {
        sunNum++;
      }
    })
    userNum.push(sunNum)
  })

  res.json({
    code: 1,
    userNum: userNum,
    count: count
  })

});

router.get('/getCpuTable', async (req, res, next) => {
  var freeMem = os.freemem() / 1024 / 1024 / 1024;
  var totalMem = os.totalmem() / 1024 / 1024 / 1024;
  res.json({
    code: 1,
    CpuNum: ((freeMem) / totalMem * 100.0).toFixed(2)
  })
})

router.get('/getMenuTimeTable', async (req, res, next) => {
  let typeList = [{ id: 1, menuTime: '早餐' }, { id: 2, menuTime: '午餐' }, { id: 3, menuTime: '晚餐' }]
  let data = await getMenuTimeTable(typeList);
  typeList = typeList.map(item => item.menuTime)
  data = data.map(item => {
    return item[0]
  })
  res.json({
    code: 1,
    data,
    typeList
  })
})

module.exports = router;